package com.lanqiao.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 张建平 on 2020/8/14.
 */
@Controller
@RequestMapping("/file")
public class FileUploadController implements ServletContextAware {

    // 在jsp中的隐式对象: application
    ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * 上传文件
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@RequestParam("file") CommonsMultipartFile file, ModelMap modelMap){

        // 获得上传文件的目标目录
        String realPath = this.servletContext.getRealPath("/upload");
        try {
            // 获得上传文件的原始文件名,但是文件名不能有中文和空格.
            String originalFilename = file.getOriginalFilename();

            modelMap.addAttribute("fileName", originalFilename);

            // 上传的目标文件
            File destFile = new File(realPath, originalFilename);

            FileItem fileItem = file.getFileItem();
            // 写出文件
            //fileItem.write(destFile); // 也可以
            file.transferTo(destFile);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "../upload_result";
    }

    /**
     * 案例2: 上传多个文件
     *
     * @param name
     * @param multipartRequest 包含所有上传文件的请求
     * @param modelMap
     * @return
     */
    @RequestMapping(value="/mutiple/upload", method = RequestMethod.POST)
    public String upload2(String name,
                          MultipartHttpServletRequest multipartRequest,
                          ModelMap modelMap){
        // 存储所有目标文件名
        List<String> fileNameList = new ArrayList<>();

        //获取服务器存储的真实路径 D:\\dev\\apache-tomcat-7.0.62\\webapps\\springmvc03\\upload\\
        String path = this.servletContext.getRealPath("/upload/");
        System.out.println("服务器存储的真实路径:" + path);

        //得到多个上传的文件
        Map<String, List<MultipartFile>> filemap = multipartRequest.getMultiFileMap();

        if(!filemap.isEmpty()){
            //循环上传的文件
            for (Map.Entry<String, List<MultipartFile>> entry : filemap.entrySet()) {
                List<MultipartFile> multipartFile = entry.getValue();

                //循环处理每个上传的文件
                for (MultipartFile file : multipartFile) {

                    //得到上传文件的原始文件名
                    String fileName = file.getOriginalFilename();

                    //得到文件的类型 *.jpg,
                    String fileType = fileName.substring(fileName.lastIndexOf(".")); //包含"."在内
                    System.out.println("文件的类型：" +fileType);

                    //新建一个文件
                    String newFileName = new Date().getTime() + fileType;
                    File destFile = new File("c:\\", newFileName);
                    fileNameList.add(newFileName);

                    try {
                        //file.transferTo(destFile); //file是MultipartFile类型
                        //commons-io.jar中的工具类
                        FileUtils.writeByteArrayToFile(destFile, file.getBytes());

                    } catch (IOException e) {
                        //e.printStackTrace();
                        return "../upload_error";
                    }
                }
            }
        }
        modelMap.addAttribute("fileNameList", fileNameList);
        return "../upload_ok";
    }


}
